#!/bin/bash

# Quick fix script for nginx service permission issues
# This fixes the "bind() to 0.0.0.0:80 failed (13: Permission denied)" error

set -e

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root
if [[ $EUID -ne 0 ]]; then
    log_error "This script requires root privileges to run"
    exit 1
fi

log_info "Fixing nginx service configuration..."

# Update systemd service to run as root
log_info "Updating nginx systemd service configuration..."
cat > /etc/systemd/system/nginx.service << 'EOF'
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/opt/RadMedical/product/tool/nginx/logs/nginx.pid
ExecStartPre=/opt/RadMedical/product/tool/nginx/sbin/nginx -t
ExecStart=/opt/RadMedical/product/tool/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
# Run master process as root to bind to privileged ports
# Worker processes will run as nginx user (configured in nginx.conf)

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd configuration
log_info "Reloading systemd configuration..."
systemctl daemon-reload

# Fix permissions for log files
log_info "Fixing log file permissions..."
if [[ -f /opt/RadMedical/product/tool/nginx/logs/error.log ]]; then
    chown nginx:nginx /opt/RadMedical/product/tool/nginx/logs/error.log
fi
if [[ -f /opt/RadMedical/product/tool/nginx/logs/access.log ]]; then
    chown nginx:nginx /opt/RadMedical/product/tool/nginx/logs/access.log
fi

# Test nginx configuration
log_info "Testing nginx configuration..."
if /opt/RadMedical/product/tool/nginx/sbin/nginx -t; then
    log_info "nginx configuration test passed"
else
    log_error "nginx configuration test failed"
    exit 1
fi

# Start nginx service
log_info "Starting nginx service..."
systemctl start nginx

# Check service status
if systemctl is-active --quiet nginx; then
    log_info "nginx service started successfully"
    systemctl status nginx
else
    log_error "nginx service failed to start"
    exit 1
fi

log_info "=========================================="
log_info "nginx service has been fixed!"
log_info "=========================================="
log_info "Service status: systemctl status nginx"
log_info "Test config: /opt/RadMedical/product/tool/nginx/sbin/nginx -t"
log_info "=========================================="

